<script setup>
import {onMounted, ref} from 'vue';
import luckysheet from "luckysheet";
import LuckyExcel from 'luckyexcel'
import {useAnalysetStore} from "@/store/index";
import {removeNullSampleSN, transformData} from "@/utils/method";
import AnalyesAPI from "@/api/system/analyes";
import dayjs from "dayjs";

let options = {
  container: "luckysheet", //luckysheet为容器id
  lang: 'zh',
  autoCalculate: true,
  data: [
    {
      "column": 10, // 列数
      "row": 10, // 列数
      "defaultRowHeight": 40, // 自定义行高
      "defaultColWidth": 100, // 自定义列宽
      "celldata": [
        // 初始化表格数据，第一行包含表头
        {"r": 0, "c": 0, "v": "样品编号",}, // A1
        {"r": 0, "c": 1, "v": "类型",}, // B1
        {"r": 0, "c": 2, "v": "初重B(g)",}, // B1
        {"r": 0, "c": 5, "v": "取样质量m(g)",}, // B1
        {"r": 0, "c": 6, "v": "干土质量m0(g)",}, // B1
        {"r": 0, "c": 7, "v": "干物质含量wdm(%)",}, // B1
        {"r": 0, "c": 8, "v": "浸出液取样体积V(mL)",}, // B1
        {"r": 0, "c": 9, "v": "终重A(g)",}, // B1
        {"r": 0, "c": 12, "v": "样品浓度C( )",}, // B1
        {"r": 0, "c": 13, "v": "样品浓度ω( )",}, // B1
        {"r": 0, "c": 14, "v": "测定结果",}, // B1
        {"r": 0, "c": 15, "v": "备注",}, // B1
        {"r": 1, "c": 2, "v": "初重1",}, // B1
        {"r": 1, "c": 3, "v": "初重2",}, // B1
        {"r": 1, "c": 4, "v": "初重3",}, // B1
        {"r": 1, "c": 9, "v": "终重1",}, // B1
        {"r": 1, "c": 10, "v": "终重2",}, // B1
        {"r": 1, "c": 11, "v": "终重3",}, // B1
      ], // 初始化数据
      "config": {
        "merge": {
          "0_0": {
            "r": 0, // 起始行
            "c": 0, // 起始列
            "rs": 2, // 跨越的行数
            "cs": 1  // 跨越的列数
          },
          "0_1": {
            "r": 0, // 起始行
            "c": 0, // 起始列
            "rs": 2, // 跨越的行数
            "cs": 1  // 跨越的列数
          },
          "0_2": {
            "r": 0, // 起始行
            "c": 1, // 起始列
            "rs": 1, // 跨越的行数
            "cs": 3  // 跨越的列数
          },
          "0_5": {
            "r": 0, // 起始行
            "c": 4, // 起始列
            "rs": 2, // 跨越的行数
            "cs": 1  // 跨越的列数
          },
          "0_6": {
            "r": 0, // 起始行
            "c": 5, // 起始列
            "rs": 2, // 跨越的行数
            "cs": 1  // 跨越的列数
          },
          "0_7": {
            "r": 0,  // 起始行
            "c": 6,  // 起始列
            "rs": 2, // 跨越的行数
            "cs": 1  // 跨越的列数
          },
          "0_8": {
            "r": 0,  // 起始行
            "c": 7,  // 起始列
            "rs": 2, // 跨越的行数
            "cs": 1  // 跨越的列数
          },
          "0_9": {
            "r": 0,  // 起始行
            "c": 8,  // 起始列
            "rs": 1, // 跨越的行数
            "cs": 3  // 跨越的列数
          },
          "0_12": {
            "r": 0,  // 起始行
            "c": 11,  // 起始列
            "rs": 2, // 跨越的行数
            "cs": 1  // 跨越的列数
          },
          "0_13": {
            "r": 0,  // 起始行
            "c": 12,  // 起始列
            "rs": 2, // 跨越的行数
            "cs": 1  // 跨越的列数
          },
          "0_14": {
            "r": 0,  // 起始行
            "c": 13,  // 起始列
            "rs": 2, // 跨越的行数
            "cs": 1  // 跨越的列数
          },
        }, // 合并单元格
        "columnlen": { // 设置列宽
          "0": 130, // 第一列宽度 150px
          "1": 130, // 第二列宽度 120px
          "2": 130, // 第三列宽度 180px
          "3": 130, // 第四列宽度 100px
          "4": 130, // 第五列宽度 200px
          "5": 130,  // 第六列宽度 150px
          "6": 130,  // 第六列宽度 150px
          "7": 150,  // 第六列宽度 150px
          "8": 130,  // 第六列宽度 150px
          "9": 130,  // 第六列宽度 150px
          "10": 130,  // 第六列宽度 150px
          "11": 130,  // 第六列宽度 150px
          "12": 130,  // 第六列宽度 150px
          "13": 130,  // 第六列宽度 150px
        }, // 表格列宽
      },
    }
  ],
  showinfobar: false, // 隐藏信息栏
  showtoolbar: true, // 隐藏工具栏
};
const tableOption = ref([
  {table: '仪器名称', id: 1,}
])
const analyseStatusPage = useAnalysetStore()
const waterForm = ref({
  bzycd: Array.from({length: 1}, () => ({
    zkyph: '',
    cdz: '',
    bzz: '',
    sfhg: '',
  })),
  pxycd: Array.from({length: 2}, () => ({
    ypbh: '',
    cdz: '',
    pjz: '',
    xdpc: '',
    zkyq: '',
    sfhg: '',
  })),
})
const record_sn = analyseStatusPage.waterForm.record_sn
const processedData = ref([])
const cdatas = ref([])
const checkDialogVisible = ref(false)
const checkTime = ref('')
const sheetData = ref('')
const jsonData = ref(null)
// 在组件挂载后初始化 Luckysheet
onMounted(() => {
  // 初始化表格
  luckysheet.create(options);
  getWaterCapacity()
});

// 获取——获取 水质容量A   工作表
const getWaterCapacity = () => {
  let josn = {
    // id: analyseStatusPage.waterForm.id,
    id: 1,
    // record_sn: record_sn,
    record_sn: 97,
  }
  AnalyesAPI.getAnalyseACapacity(josn).then(data => {
    // console.log('获取水质容量 A单', data)
    // waterForm.value = data
    // sheetData.value = data.configs
    // options.data = sheetData.value
    // luckysheet.create(options);
    // processedData.value = data.adatas
  })
}

const loadDataFromLocal = () => {
  sheetData.value = luckysheet.getLuckysheetfile();
  options.data = sheetData.value; // 将字符串解析为 JSON
  console.log(options.data)
  const data = options.data[0].data.map(row => {
    return row
        .map(cell => {
          return cell ? {
            field: cell.m || "默认字段",
            value: cell.v || null
          } : null;
        })
        .filter(cell => cell !== null); // 删除 null 值
  });
  console.log(data);
  // 调用函数
  processedData.value = processData(data);
  cdatas.value = removeNullSampleSN(transformData(processedData.value))
  console.log(cdatas.value)

//   调保存新增接口
  AnalyesAPI.addWaterCapacity({
    ...waterForm.value,
    // record_sn: record_sn,
    record_sn: 97,
    // id: analyseStatusPage.waterForm.id,
    task_id: analyseStatusPage.waterForm.taskId,
    configs: sheetData.value,
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    adatas: processedData.value,
    cdatas: cdatas.value,
  }).then(data => {
    console.log('调接口拿数据', data)
  })
};

const processData = (data) => {
  if (!data || data.length < 2) {
    return [];
  }
  // 提取表头字段
  const headers = [];
  for (let i = 0; i < data[0].length; i++) {
    const field1 = data[0][i]?.field || ""; // 第一行的字段
    const field2 = data[1][i]?.field || ""; // 第二行的字段

    // 优先使用第二行字段，如果为空则使用第一行字段
    const header = (field1 === "默认字段" || field1 === "") ? field2 : field1;

    // 跳过无效字段
    if (header !== "默认字段" && header.trim() !== "") {
      headers.push(header);
    }
  }

  console.log(headers)
  // 处理数据部分
  const result = data.slice(2).map(row => {
    const rowObject = {};
    headers.forEach((header, index) => {
      const cell = row[index];
      rowObject[header] = cell?.value ?? null; // 如果没有值，则默认 null
    });
    return rowObject;
  });

  // 过滤掉空行（所有字段均为 null 的行）
  return result.filter(row =>
      Object.values(row).some(value => value !== null)
  );
};


// 用于获取最新的表格数据
const getUpdatedData = () => {
  checkDialogVisible.value = true
};
const handleCheckClose = () => {
  checkDialogVisible.value = false
}

// 确认提交
const handleSubmit = () => {
  console.log(checkTime.value)
  const formattedDate = checkTime.value ? dayjs(checkTime.value).format('YYYY-MM-DD') : '';
  console.log(formattedDate); // "2025-02-06"
  console.log(analyseStatusPage.waterForm.id)
  AnalyesAPI.handleCheckTimeData({
    id: analyseStatusPage.waterForm.add_form_id,
    submit_date: formattedDate
  }).then(data => {
    if (data === 1) {
      ElMessage.success('提交成功！')
      checkDialogVisible.value = false
    }
  })
}

// 上传文件
const loadExcel = (evt) => {
  const files = evt.target.files
  console.log(files)
  if (files == null || files.length == 0) {
    alert('No files wait for import')
    return
  }
  let name = files[0].name
  let suffixArr = name.split('.'),
      suffix = suffixArr[suffixArr.length - 1]
  if (suffix != 'xlsx') {
    alert('Currently only supports the import of xlsx files')
    return
  }
  LuckyExcel.transformExcelToLucky(files[0], function (exportJson, luckysheetfile) {
    if (exportJson.sheets == null || exportJson.sheets.length == 0) {
      alert('Failed to read the content of the excel file, currently does not support xls files!')
      return
    }
    console.log('exportJson', exportJson.sheets)
    jsonData.value = exportJson

    luckysheet.destroy()
    luckysheet.create({
      container: 'luckysheet', //luckysheet is the container id
      showinfobar: false,
      data: exportJson.sheets,
      title: exportJson.info.name,
      userInfo: exportJson.info.name.creator
    })
  })
}

const handleSwitch = () => {
  switchAB.value = !switchAB.value
}

</script>

<template>
  <div class="card">
    <el-card class="box-card">
      <h1 style="text-align: center">土壤 重量法分析原始记录</h1>
      <div>SXLPHJ/JL/CX-22-97</div>
      <table class="table">
        <tr>
          <td colspan="1">任务编号</td>
          <td colspan="3">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.task_name"/>
          </td>
          <td colspan="1" style="width: 8%;">采样日期</td>
          <td colspan="2">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.sampling_time"/>
          </td>
          <td colspan="1" style="width: 8%;">分析日期</td>
          <td colspan="11">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.anal_time"/>
          </td>
        </tr>
        <tr>
          <td colspan="1">分析方法</td>
          <td colspan="3">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.method"/>
          </td>
          <td colspan="1" style="width: 8%;">分析项目</td>
          <td colspan="2">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.fxxm"/>
          </td>
          <td colspan="1" style="width: 8%;">检出限</td>
          <td colspan="11">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.limit_val"/>
          </td>
        </tr>
        <tr>
          <td colspan="1">恒重仪器</td>
          <td colspan="1">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.hz_device_name"/>
          </td>
          <td colspan="1" style="width: 5%;">仪器型号</td>
          <td colspan="1">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.hz_device_model"/>
          </td>
          <td colspan="1" style="width: 8%;">仪器编号</td>
          <td colspan="2">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.hz_device_number"/>
          </td>
          <td colspan="1" style="width: 8%;">环境温度</td>
          <td colspan="11">
            <el-input style="width: 150px;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.temperature">
              <template #append>
                <span style="background-color: transparent;color: black">℃</span>
              </template>
            </el-input>
          </td>
        </tr>
        <tr>
          <td colspan="1">天平名称</td>
          <td colspan="1">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.device_name"/>
          </td>
          <td colspan="1" style="width: 5%;">天平型号</td>
          <td colspan="1">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.device_model"/>
          </td>
          <td colspan="1" style="width: 8%;">天平编号</td>
          <td colspan="2">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.device_number"/>
          </td>
          <td colspan="1" style="width: 8%;">环境湿度</td>
          <td colspan="11">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.humidity">
              <template #append>
                <span style="background-color: transparent;color: black">%RH</span>
              </template>
            </el-input>
          </td>
        </tr>
        <tr>
          <td colspan="1">前处理过程</td>
          <td colspan="6">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.process"/>
          </td>
          <td colspan="1" style="width: 8%;">计算公式</td>
          <td colspan="17">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.js_formula"/>
          </td>
        </tr>
        <tr>
          <td colspan="1">备注</td>
          <td colspan="21">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.notes"/>
          </td>
        </tr>
      </table>
      <div id="luckysheet" style="width:100%;height:500px;"></div>
      <table class="table">
        <tr>
          <td colspan="6">标准样品测定</td>
        </tr>
        <tr>
          <td>质控样批号</td>
          <td>测定值( )</td>
          <td colspan="2">标准值( )</td>
          <td colspan="2">是否合格</td>
        </tr>
        <tr v-for="(item,index) in waterForm.bzycd" :key="index">
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="item.zkyph"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="item.cdz"/>
          </td>
          <td colspan="2">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="item.bzz"/>
          </td>
          <td colspan="2">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="item.sfhg"/>
          </td>
        </tr>
        <tr>
          <td colspan="6">平行样测定</td>
        </tr>
        <tr>
          <td>样品编号</td>
          <td>测定值( )</td>
          <td>平均值( )</td>
          <td>相对偏差（%）</td>
          <td>质控要求</td>
          <td>是否合格</td>
        </tr>
        <tr v-for="(item,index) in waterForm.pxycd" :key="index">
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="item.ypbh"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="item.cdz"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="item.pjz"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="item.xdpc"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="item.zkyq"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="item.sfhg"/>
          </td>
        </tr>
      </table>
    </el-card>

    <el-card class="box-card" style="margin-top: 30px">
      <div style="display: flex;justify-content: flex-end">
        <!-- <el-button @click="handleSwitch">
          {{ switchAB ? 'B面' : 'A面' }}
        </el-button> -->
        <div>
          <el-button>取消</el-button>
          <el-button>新增</el-button>
          <el-button>复制并新增</el-button>
          <el-button @click="loadDataFromLocal">保存</el-button>
          <el-button type="primary" @click="getUpdatedData">提交</el-button>
        </div>
      </div>
    </el-card>
    <!--    提交校核-->
    <el-dialog title="提交校核" v-model="checkDialogVisible" width="30%" center
               :before-close="handleCheckClose">
      <div class="check">
        <!--        头部-->
        <div class="check-header" style="display: flex;align-items: center;margin-bottom: 20px">
          表单填写日期：
          <el-date-picker
              style="border: 1px solid #cccccc;border-radius: 6px;width: 80%;"
              type="date"
              placeholder="请选择"
              v-model="checkTime"
          />
        </div>
        <div class="check-footer">
          <el-button style="width: 48%;" @click="handleCheckClose">取消</el-button>
          <el-button type="primary" style="width: 48%;" @click="handleSubmit">确认</el-button>
        </div>
      </div>
    </el-dialog>
  </div>

</template>

<style scoped>
.card {
  padding: 20px 25px;
}

.table {
  width: 100%;
  border-collapse: collapse;
  /* 表格边框合并 */
  text-align: left;
  /* 默认左对齐 */
  font-size: 14px;
  /* 字体大小 */
  color: #606266;
  /* 默认字体颜色 */
  margin-bottom: 20px;
}

.table th,
.table td {
  border: 1px solid #c2bfbf;
  /* 表格单元格边框颜色 */
  padding: 12px;
  /* 单元格内边距 */
  text-align: center;
}

.table th {
  background: #f5f7fa;
  /* 表头背景色 */
  font-weight: 600;
  /* 表头字体加粗 */
  color: #303133;
  /* 表头字体颜色 */
  text-align: center;
  /* 表头居中 */
}


.table-td {
  display: flex;
}

::v-deep .el-input__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-select__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-input-group__append {
  background-color: transparent;
  box-shadow: none;
}
</style>
